package com.magicsharpmod.item.custom;

import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUsageContext;
import net.minecraft.text.Text;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.util.TypedActionResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;

import java.util.List;
import java.util.Objects;

public class Prospector extends Item {
    public Prospector(Settings settings) {
        super(settings);
    }

    //
    @Override
    public ActionResult useOnBlock(ItemUsageContext context) {
        World world = context.getWorld();
        //这个可以获得该世界所有的玩家
        List<? extends PlayerEntity> AllPlayers = world.getPlayers();
        //如果世界是服务端的话
        if(!world.isClient){
            //方块信息
            BlockPos blockPos = context.getBlockPos();
            //获得触发该操作的特定玩家
            PlayerEntity player = context.getPlayer();
            //布尔值
            boolean found = false;
            for (int i = -64; i <blockPos.getY()+64; i++) {
                //这个是方块的种类
                BlockState blockState = context.getWorld().getBlockState(blockPos.down(i));
                if(isRightBlock(blockState)){
                    assert player != null;
                    outputMessage(blockPos.down(i),player,blockState.getBlock());
                    found = true;
                }
            }
            if(!found){
                assert player != null;
                player.sendMessage(Text.literal("No found Any Ore"));
            }
        }

        //设置工具使用之后耐久减少1
        context.getStack().damage(1, Objects.requireNonNull(context.getPlayer()),
                playerEntity -> playerEntity.sendToolBreakStatus(playerEntity.getActiveHand()));
        return ActionResult.SUCCESS;
    }

    //成功找到方块后发信息
    private void outputMessage(BlockPos down, PlayerEntity player, Block block) {
        player.sendMessage(Text.literal("Found"+ block.asItem().getName().getString()+ "at" +
                "("+ down.getX()+","+ down.getY()+"," +down.getZ()+")!"), false);
    }


    private boolean isRightBlock(BlockState blockState) {
        return blockState.isOf(Blocks.IRON_ORE)||blockState.isOf(Blocks.DIAMOND_ORE);
    }
}
